package org.mspring.mlog.service;

import java.io.IOException;
import java.net.URISyntaxException;

import javax.transaction.Transactional;

import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.mspring.mlog.entity.Twitter;
import org.mspring.platform.config.ConfigService;
import org.mspring.platform.security.entity.User;
import org.mspring.platform.security.exception.UNLoginException;
import org.mspring.platform.utils.StringUtils;
import org.mspring.platform.utils.http.HttpUtils;
import org.mspring.platform.weibo.exception.OAuthException;
import org.mspring.platform.weibo.tencent.TencentUserinfoService;
import org.mspring.platform.weibo.tencent.TencentWeiboService;
import org.mspring.platform.weibo.tencent.entity.TencentUserinfo;
import org.mspring.platform.weibo.tencent.entity.dto.APIResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 * @author Gao Youbo
 * @since 2014年5月23日
 */
@Service
@Transactional
public class WeiboService {

    private static final Logger log = LoggerFactory.getLogger(WeiboService.class);

    @Autowired
    private TencentWeiboService tencentWeiboService;
    @Autowired
    private TencentUserinfoService tencentUserinfoService;
    @Autowired
    private ConfigService configService;

    public boolean add(User user, Twitter twitter) throws UNLoginException, OAuthException {
        if (twitter == null) {
            return false;
        }
        StringBuilder content = new StringBuilder();
        content.append(twitter.getContent());
        content.append(" 来自于:");
        content.append("#").append(configService.getConfig("sitename")).append("#");
        content.append(configService.getConfig("siteurl"));

        if (StringUtils.isBlank(twitter.getImage())) {
            return add(user, content.toString(), twitter.getIp());
        } else {
            return addPic(user, content.toString(), twitter.getImage(), twitter.getImage());
        }
    }

    public boolean add(User user, String content, String clientip) throws UNLoginException, OAuthException {
        if (StringUtils.isBlank(clientip)) {
            throw new IllegalArgumentException("clientip不能为空");
        }
        TencentUserinfo userinfo = tencentUserinfoService.findByUserId(user.getId());
        if (userinfo == null) {
            log.warn("用户尚未绑定微博,userId={}, username={}", user.getId(), user.getName());
            return false;
        }
        APIResult result = tencentWeiboService.add(userinfo, content, clientip);
        return result.isSuccess();
    }

    public boolean addPic(User user, String content, String imgUrl, String clientip) throws UNLoginException, OAuthException {
        if (StringUtils.isBlank(clientip)) {
            throw new IllegalArgumentException("clientip不能为空");
        }
        TencentUserinfo userinfo = tencentUserinfoService.findByUserId(user.getId());
        if (userinfo == null) {
            log.warn("用户尚未绑定微博,userId={}, username={}", user.getId(), user.getName());
            return false;
        }
        byte[] pic = null;
        if (StringUtils.isNotBlank(imgUrl)) {
            try {
                HttpResponse httpResponse = HttpUtils.get(imgUrl, null, -1, configService.getConfig("siteurl"));
                pic = EntityUtils.toByteArray(httpResponse.getEntity());
            } catch (IOException | URISyntaxException e) {
                log.error("获取远程图片失败:url=" + imgUrl, e);
            }
        }
        APIResult result = tencentWeiboService.addPic(userinfo, content, pic, clientip);
        return result.isSuccess();
    }
}
